package com.homepage.web.rest;

import com.homepage.repository.EmployeePortraitRepository;
import com.homepage.service.EmployeePortraitService;
import com.homepage.service.dto.EmployeePortraitDTO;
import com.homepage.util.HeaderUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;


/**
 * REST controller for managing {@link com.homepage.domain.EmployeePortrait}.
 */
@RestController
@RequestMapping("/company")
public class EmployeePortraitResource {

    private final Logger log = LoggerFactory.getLogger(EmployeePortraitResource.class);

    private static final String ENTITY_NAME = "employeePortrait";

    @Value("${common.clientApp.name}")
    private String applicationName;

    private final EmployeePortraitService employeePortraitService;

    private final EmployeePortraitRepository employeePortraitRepository;

    public EmployeePortraitResource(
        EmployeePortraitService employeePortraitService,
        EmployeePortraitRepository employeePortraitRepository
    ) {
        this.employeePortraitService = employeePortraitService;
        this.employeePortraitRepository = employeePortraitRepository;
    }


    @PutMapping(value = "/employee/{id}/portrait", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
    @ResponseBody
    public ResponseEntity<ModelMap>  createEmployeePortrait(@PathVariable Long id,
                                                       @RequestPart MultipartFile picData) throws URISyntaxException, IOException {
        log.debug("REST request to save employee portrait" );
        InputStream is = picData.getInputStream();
        String contentType = picData.getContentType();
        String fileName = picData.getOriginalFilename();
        log.debug("store image : " );
        byte[] pictureData = new byte[(int) picData.getSize()];
        int length = is.read(pictureData);
        EmployeePortraitDTO employeePortraitDTO = new EmployeePortraitDTO();
        employeePortraitDTO.setEmployeeId(id);
        employeePortraitDTO.setPortraitImage(pictureData);
        employeePortraitDTO.setPortraitImageContentType(contentType);

        employeePortraitService.save(employeePortraitDTO);

        ModelMap modelMap = new ModelMap();
        modelMap.addAttribute("code", HttpStatus.CREATED.value());
        return ResponseEntity
                .created(new URI("/employee/"+id+"/portrait" ))
                .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME,  String.valueOf(id)))
                .body(modelMap);
    }



    /**
     * {@code GET  /employee-portraits} : get all the employeePortraits.
     *
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of employeePortraits in body.
     */
    @GetMapping("/employee/{id}/portrait")
    public ResponseEntity<byte[]> getEmployeePortraitByEmployeeId(@PathVariable(value = "id")  long id){
        EmployeePortraitDTO employeePortraitDTO = employeePortraitService.findOneByEmployeeId(id).get();
        if(employeePortraitDTO == null)
        {
            return new ResponseEntity(null,null, HttpStatus.NOT_FOUND);
        }
        HttpHeaders headers = new HttpHeaders();
        if(employeePortraitDTO.getPortraitImageContentType().equalsIgnoreCase(MediaType.IMAGE_JPEG_VALUE))
            headers.setContentType(MediaType.IMAGE_JPEG);
        if(employeePortraitDTO.getPortraitImageContentType().equalsIgnoreCase(MediaType.IMAGE_PNG_VALUE))
            headers.setContentType(MediaType.IMAGE_PNG);
        headers.setContentLength(employeePortraitDTO.getPortraitImage().length);

        return new ResponseEntity<byte[]>(employeePortraitDTO.getPortraitImage(), headers, HttpStatus.OK);
    }


    /**
     * {@code DELETE  /employee-portraits/:id} : delete the "id" employeePortrait.
     *
     * @param id the id of the employeePortraitDTO to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/employee-portraits/{id}")
    public ResponseEntity<Void> deleteEmployeePortrait(@PathVariable Long id) {
        log.debug("REST request to delete EmployeePortrait : {}", id);
        employeePortraitService.delete(id);
        return ResponseEntity
            .noContent()
            .headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString()))
            .build();
    }
}
